package com.fa4j.system.settings.controller;

import com.fa4j.common.base.exception.CommonRequestError;
import com.fa4j.common.base.model.CommonConstants;
import com.fa4j.common.base.model.Page;
import com.fa4j.common.base.model.RemoveCmd;
import com.fa4j.common.web.annotation.ApiMethod;
import com.fa4j.common.web.model.AppType;
import com.fa4j.system.login.util.LoginUtil;
import com.fa4j.system.settings.model.*;
import com.fa4j.system.settings.repository.DictRepository;
import com.fa4j.system.settings.service.DictService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;


@RestController
@RequestMapping("/system/settings/dict")
@RequiredArgsConstructor
public class DictController {

    private final DictService dictService;
    private final DictRepository dictRepository;


    @ApiMethod(name = "系统设置字典-分页查询", type = AppType.MANAGE)
    @GetMapping("page")
    public Page<Dict> page(DictQuery query) {
        query.setParentId(CommonConstants.TREE_ROOT_ID);
        return dictRepository.queryPage(query);
    }


    @ApiMethod(name = "系统设置字典-字典树查询", type = AppType.MANAGE)
    @GetMapping("{rootId}/tree")
    public List<Dict> queryTree(@PathVariable Integer rootId, Integer level) {
        return dictRepository.queryTreeByRootId(rootId, level);
    }


    @ApiMethod(name = "系统设置字典-根据rootCode查询", type = AppType.MANAGE, auth = ApiMethod.Switch.OFF)
    @GetMapping("tree/byRootCode")
    public List<Dict> queryTreeByRootCode(String rootCode, Integer level) {
        Optional<Dict> root = dictRepository.findByParentIdAndCode(CommonConstants.TREE_ROOT_ID, rootCode);
        if (root.isPresent()) {
            return dictRepository.queryTreeByRootId(root.get().getId(), level);
        } else {
            return List.of();
        }
    }

    @ApiMethod(name = "系统设置字典-子级查询", type = AppType.MANAGE)
    @GetMapping("{parentId}/children")
    public List<Dict> queryChildren(@PathVariable Integer parentId) {
        return dictRepository.queryByParentId(parentId);
    }

    @ApiMethod(name = "系统设置-字典详情查询", type = AppType.MANAGE)
    @GetMapping("{id}")
    public Dict detail(@PathVariable Integer id) {
        return dictRepository.findById(id)
                .orElseThrow(() -> CommonRequestError.NOT_FOUND.build("系统字典"));
    }

    @ApiMethod(name = "系统设置字典-创建", type = AppType.MANAGE)
    @PostMapping
    public Dict create(@Valid @RequestBody DictCreateCmd cmd) {
        return dictService.create(cmd);
    }

    @ApiMethod(name = "系统设置字典-编辑", type = AppType.MANAGE)
    @PatchMapping
    public Dict modify(@Valid @RequestBody DictModifyCmd cmd) {
        return dictService.modify(cmd);
    }

    @ApiMethod(name = "系统设置字典-删除", type = AppType.MANAGE)
    @DeleteMapping("{id}")
    public Dict remove(@PathVariable Integer id) {
        return dictService.remove(RemoveCmd.of(id, LoginUtil.getAccountId()));
    }

}
